import { fileURLToPath, URL } from 'node:url'

import { defineConfig, loadEnv } from 'vite'
import process from 'process'
import Components from 'unplugin-vue-components/vite'
import AutoImport from 'unplugin-auto-import/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import vue from '@vitejs/plugin-vue'

// https://vitejs.dev/config/
export default ({ mode }: { mode: any }) => {
  const env = loadEnv(mode, process.cwd()) //在vite中获取环境变量的方法
  return defineConfig({
    plugins: [
      // 解析单文件组件的插件
      vue(),
      AutoImport({
        resolvers: [ElementPlusResolver()]
      }),
      // 自动导入的插件，解析器可以是 vant element and-vue
      Components({
        dts: false,
        // 原因：Toast Confirm 这类组件的样式还是需要单独引入，样式全局引入了，关闭自动引入
        resolvers: [ElementPlusResolver()]
      })
    ],
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url))
      }
    },
    server: {
      host: 'localhost',
      port: 8080,
      open: true,
      cors: true, //允许跨域
      proxy: {
        //配置代理
        '/api': {
          target: env.VITE_APP_BASE_URL, //自动读取环境变量中的基地址
          changeOrigin: true,
          rewrite: (path) => path.replace('/api/', '/') //路径重写
        }
      }
    }
  })
}
